Page({
  data: {
    time: true,
    endTime: false,
    count: false,
    qaList: [],
    lastReply: null, // 最新回复
    mostReplied: null // 回复最多的问题
  },

  // Tab切换事件
  onTime() {
    this.setData({ time: true, endTime: false, count: false });
  },
  onEndTime() {
    this.setData({ time: false, endTime: true, count: false });
  },
  onCount() {
    this.setData({ time: false, endTime: false, count: true });
  },

  // 导航跳转
  toQa() {
    wx.navigateTo({ url: '/index/pages/kefu/kefu' });
  },
  toParticulars(e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({ url: `/index/pages/particulars/particulars?id=${id}` });
  },
  onReply() {
    wx.navigateTo({ url: '/index/pages/reply/reply' });
  },
  onDesc() {
    wx.navigateTo({ url: '/index/pages/particulars/particulars' });
  },

  // 获取单个问题的回复数量
  getReplyCount(questionId, callback) {
    wx.request({
      url: `http://localhost:8080/reply/selectCountByQuestionId/${questionId}`,
      method: 'GET',
      success(res) {
        callback(res.data?.code === 200 ? res.data.data : 0);
      },
      fail() { callback(0); }
    });
  },

  // 获取最新回复（按时间排序）
  getLatestReply() {
    wx.request({
      url: 'http://localhost:8080/reply/pages', // 后端获取所有回复的接口
      method: 'GET',
      success: (res) => {
        console.log('回复接口返回数据：', res.data); // 新增打印，检查接口返回
        if (res.data?.code === 200 && Array.isArray(res.data.data)) {
          const allReplies = res.data.data;
          if (allReplies.length === 0) {
            this.setData({ lastReply: null });
            return;
          }
          // 按回复时间降序排序（最新的在前面）
          const sorted = allReplies.sort((a, b) => {
            return new Date(b.replyTime) - new Date(a.replyTime);
          });
          // 获取该问题的总回复数
          this.getReplyCount(sorted[0].questionId, (count) => {
            this.setData({
              lastReply: { ...sorted[0], questionReplyCount: count }
            });
          });
        } else {
          this.setData({ lastReply: null });
        }
      },
      fail: () => {
        this.setData({ lastReply: null });
      }
    });
  },

  // 获取回复最多的问题
  getMostRepliedQuestion() {
    const { qaList } = this.data;
    if (qaList.length === 0) {
      this.setData({ mostReplied: null });
      return;
    }
    // 按回复数降序排序
    const sorted = [...qaList].sort((a, b) => (b.replyCount || 0) - (a.replyCount || 0));
    this.setData({ mostReplied: sorted[0] });
  },

  // 加载问答列表
  loadQaList() {
    wx.request({
      url: 'http://localhost:8080/question/pages',
      method: 'GET',
      success: (res) => {
        if (res.data?.code === 200 && Array.isArray(res.data.data?.list)) {
          let qaList = res.data.data.list;
          let countLoaded = 0;

          if (qaList.length === 0) {
            this.setData({ qaList });
            return;
          }

          // 批量获取回复数
          qaList.forEach((item, idx) => {
            this.getReplyCount(item.id, (count) => {
              qaList[idx].replyCount = count;
              if (++countLoaded === qaList.length) {
                this.setData({ qaList });
                this.getMostRepliedQuestion(); // 计算回复最多的问题
              }
            });
          });
        }
      },
      fail: (err) => {
        console.error('加载问答列表失败:', err);
      }
    });
  },

  // 生命周期
  onLoad() {
    this.loadQaList();
    this.getLatestReply();
  },
  onShow() {
    this.loadQaList(); // 页面显示时刷新数据
    this.getLatestReply();
  },
  onPullDownRefresh() {
    this.loadQaList();
    this.getLatestReply();
    wx.stopPullDownRefresh();
  },
  onReachBottom() {
    // 可添加分页加载逻辑
  },
  onShareAppMessage() {
    return { title: '问答列表' };
  }
});